import 'package:flutter/material.dart';
import 'package:magic_car/inspect/inspectorlist.dart';
import 'package:magic_car/jiance/inspectresults.dart';
import 'package:magic_car/jiance/inspectstart.dart';
import 'package:magic_car/jiance/papularInspects.dart';
import 'package:magic_car/jiance/start.dart';
import 'package:magic_car/site/site.dart';
import 'package:magic_car/site/sitelist.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

class JIanceDetailPage extends StatefulWidget {
  final String oid;
  JIanceDetailPage(this.oid);
  State<StatefulWidget> createState() {
    return new DetailState(this.oid);
  }
}

class DetailState extends State<JIanceDetailPage> {
  final String oid;
  DetailState(this.oid);
  List formList;
  Map orderinfo = new Map();
  String price = "0.00";
  String status = "订单状态";
  String order_sn = "订单编号";
  String handelStr = "指派";
  String statuscode = "0";
  String role = '';
  String is_accpect;

  Map jianceres ;
  String isstart="";

  String income = "0.00";
  String peifu = "0.00";
  initState() {
    super.initState();
    formList = [
      {
        "title": '预约项目',
        'sub_title': '预约项目',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '联系人',
        'sub_title': '联系人',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '联系电话',
        'sub_title': '联系电话',
        'cantap': 1,
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '预约时间',
        'sub_title': '预约时间',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '品牌',
        'sub_title': '品牌',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '预约车型',
        'sub_title': '预约车型',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车价',
        'sub_title': '车价',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '下单时间',
        'sub_title': '下单时间',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '合伙人',
        'sub_title': '合伙人',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '站点',
        'sub_title': '站点',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '检测师',
        'sub_title': '检测师',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '指派时间',
        'sub_title': '指派时间',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '检测师确认订单时间',
        'sub_title': '检测师确认订单时间',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
    ];
    loadOrderInfo();
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    print(formList);
    Widget content;
    for (var i = 0; i < formList.length; i++) {
      var item = formList[i];
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
          child: Container(
              // color: Colors.white,
              height: 30,
              child: new GestureDetector(
                  onTap: () async {
                    print('点击索引' + i.toString());
                    if (i == 2) {
                      //拨打电话
                      String url = 'tel:' + item['sub_title'];
                      if (await canLaunch(url)) {
                        await launch(url);
                      } else {
                        throw 'Could not launch $url';
                      }
                    }
                  },
                  child: new Row(
                    children: <Widget>[
                      Expanded(
                        child: new Padding(
                            padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                            child: new Text(
                              item['title'],
                              style: TextStyle(
                                  fontSize: 12,
                                  color: Color.fromRGBO(51, 51, 51, 1)),
                            )),
                        flex: 1,
                      ),
                      new Padding(
                          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                          child: new Text(
                            //'1212121',
                            item['sub_title'],
                            style: TextStyle(
                                fontSize: 12,
                                color: Color.fromRGBO(51, 51, 51, 1)),
                          )),
                    ],
                  )))));
    }
    // return tiles;
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  //设置订单开始
  setStart() {
    // Map<String, String> map = new Map();
    // map['id'] = this.oid;
    // //  SharedPreferences pref = await SharedPreferences.getInstance();
    // //  map["id"]=pref.getString('uid');
    // //  map["type"]="0";

    // HttpHelper.post(HttpHelper.API_UpdateOrderStart, (data) async {
    //   if (data != null) {
    //     print(data);
    //     if (data["code"].toString() == "1"||data["code"].toString() == "0") {
    //       Navigator.of(context)
    //                       .push(new MaterialPageRoute(builder: (_) {
    //                     return new Papularinspects(this.oid,1);
    //                   }));
    //     }
    //     if(data["code"].toString() == "2"||data["code"].toString() == "3"){
    //       Navigator.of(context)
    //                       .push(new MaterialPageRoute(builder: (_) {
    //                     return new PapularinspectReults(this.oid,1);
    //                   }));
    //     }
    //   }
    // }, params: map);
    if (statuscode == "0") {
      //StartPicPage
      Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
        return new StartPicPage(this.oid);
      }));
    }
    if (statuscode == "1" && isstart=="1") {
      Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
         return new PapularinspectReults(this.oid, 1);
       // return new Papularinspects(this.oid, 1, {});
      }));
    }
    if (statuscode == "2" || statuscode == "3") {
      Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
        return new PapularinspectReults(this.oid, 1);
      }));
    }
  }

  //加载订单信息
  loadOrderInfo() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    SharedPreferences pref = await SharedPreferences.getInstance();
    String roles = pref.getString('role');
    print(roles);
    print('角色');
    // setState(() {
    //   role = role;
    // });
    //  map["id"]=pref.getString('uid');
    //  map["type"]="0";

    HttpHelper.post(HttpHelper.API_OrderDetail, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          List oldlist = formList;
          var orderinfo = data["info"];
          for (var i = 0; i < oldlist.length; i++) {
            var item = oldlist[i];
            var str = "";
            if (i == 0)
              str = "${orderinfo["test_type"]}";
            else if (i == 1)
              str = "${orderinfo["name"]}" ;
            else if (i == 2)
              str ="${orderinfo["phone_num"]}" ;
            else if (i == 3)
              str = "${orderinfo["add_time"]}" ;
            else if (i == 4)
              str = orderinfo['brand_id']=="0"?"暂无":  "${orderinfo["brand_string"]["name"]}" ;
            else if (i == 5)
              str = orderinfo['cartype_id']=="0"?"暂无": "${orderinfo["cartype_string"]["name"]}" ;
            else if (i == 6)
              str ="${orderinfo["carprice"]}" ;
            else if (i == 7)
              str = "${orderinfo["order_time"]}" ;
            else if (i == 8)
              str = "${orderinfo['part_name']}" ;
            else if (i == 9)
              str ="${orderinfo['site_name']}" ;
            else if (i == 10)
              str = "${orderinfo['inpsetor_name']}";
            else if (i == 11)
              str = "${orderinfo['assign_time']}" ;
            else if (i == 12) str ="${orderinfo['accept_time']}" ;

            item["sub_title"] = str;
          }
          String tempStr = "";
          String statu = data["info"]["status"].toString();
          String isassign = data["info"]["is_assign"].toString();
          String isacpt = data["info"]["is_accept"].toString();
          if (isassign == "0") {
            tempStr = "未指派";
          } else if (isacpt == "0") {
            tempStr = '已指派，检测师确认订单中';
          } else {
            tempStr = '检测师已确认订单';
          }

          if (int.parse(statu) > 1) {
            tempStr = '订单已完成';
          }
          // if (statu == "0") {
          //   tempStr = "待处理";
          // } else if (statu == "1") {
          //   tempStr = "进行中";
          //   handelStr = "继续检测";
          // } else if (statu == "2") {
          //   tempStr = "待评价";
          //   handelStr = "查看报告";
          // } else {
          //   tempStr = "已完成";
          //   handelStr = "查看报告";
          // }
          setState(() {
            isstart = data["info"]["is_start"];
            formList = oldlist;
            orderinfo = data["info"];
            price = data["info"]["orderPrice"];
            status = tempStr;
            order_sn = data["info"]["order_sn"];
            statuscode = statu;
            role = roles;
            is_accpect = data["info"]["is_accept"].toString();
            income = data['info'].containsKey('income_arr')
                ? data['info']['income_arr']['partner'].toString()
                : '0.00';
            peifu = data['info'].containsKey('peifu_arr')
                ? data['info']['peifu_arr']['partner'].toString()
                : '0.00';
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  /**
   * 指派
   */
  assign(type) {
    if (type == 1) {
      Navigator.push<Object>(context,
          new MaterialPageRoute(builder: (BuildContext context) {
        return SiteListPage(this.oid);
      })).then((Object result) {
        loadOrderInfo();
      });
      //指派到站点
      // Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
      //   return new SiteListPage(this.oid);
      // }));
    } else {
      //指派到检测师
      Navigator.push<Object>(context,
          new MaterialPageRoute(builder: (BuildContext context) {
        return InspectorListPage(this.oid);
      })).then((Object result) {
        loadOrderInfo();
      });
      // Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
      //   return new InspectorListPage(this.oid);
      // }));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            '订单详情',
            style: TextStyle(color: Colors.white),
          ),
          backgroundColor: Color.fromRGBO(33, 192, 193, 1),
          elevation: 0,
          iconTheme: new IconThemeData(color: Colors.white),
        ),
        body: Container(
          child: new ListView(
            children: <Widget>[
              Container(
                height: 150,
                color: Color.fromRGBO(33, 192, 193, 1),
                child: Padding(
                  padding: new EdgeInsets.fromLTRB(15, 50, 15, 10),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: new EdgeInsets.all(10),
                        child: Text(
                          status,
                          style: TextStyle(fontSize: 18, color: Colors.white),
                        ),
                      ),
                      Padding(
                        padding: new EdgeInsets.all(10),
                        child: Text(
                          '订单编号：' + order_sn,
                          style: TextStyle(fontSize: 13, color: Colors.white),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              Container(
                height: 10,
                color: Color.fromRGBO(238, 238, 238, 1),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(13, 15, 15, 15),
                  child: Container(
                      // padding: new EdgeInsets.all(15),
                      height: 20,
                      // color: Color.fromRGBO(27, 182, 251, 1),
                      child: new Text(
                        '1',
                        style: TextStyle(
                            color: Color.fromRGBO(27, 182, 251, 1),
                            backgroundColor: Color.fromRGBO(27, 182, 251, 1)),
                      ))),
              Padding(
                  padding: new EdgeInsets.fromLTRB(15, 1, 15, 15),
                  child: buildcontent()),
              Padding(
                padding: new EdgeInsets.fromLTRB(0, 15, 25, 10),
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    '检测金额：¥' + price,
                    style: TextStyle(
                        fontSize: 12, color: Color.fromRGBO(51, 51, 51, 1)),
                  ),
                ),
              ),
              int.parse(statuscode) > 1
                  ? Padding(
                      padding: new EdgeInsets.fromLTRB(0, 0, 25, 10),
                      child: Align(
                        alignment: Alignment.centerRight,
                        child: Text(
                          '订单收益：¥' + income,
                          style: TextStyle(
                              fontSize: 12,
                              color: Color.fromRGBO(51, 51, 51, 1)),
                        ),
                      ),
                    )
                  : new Container(height: 0),
              int.parse(statuscode) > 1
                  ? Padding(
                      padding: new EdgeInsets.fromLTRB(0, 0, 25, 10),
                      child: Align(
                        alignment: Alignment.centerRight,
                        child: Text(
                          double.parse(peifu)>100?"担责比例：¥${peifu}":"担责比例：${peifu}%",
                          //'担责比例：${peifu}' ,
                          style: TextStyle(
                              fontSize: 12,
                              color: Color.fromRGBO(51, 51, 51, 1)),
                        ),
                      ),
                    )
                  : new Container(height: 0),
              is_accpect == "0"
                  ? Padding(
                      padding: new EdgeInsets.fromLTRB(35, 10, 35, 20),
                      child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: new RaisedButton.icon(
                            icon: new Image.asset(
                                'resource/images/user/answer.png'),
                            label: Text(
                              '指派检测师',
                              style: TextStyle(fontSize: 15),
                            ),
                            color: Color.fromRGBO(33, 192, 193, 1),
                            textColor: Colors.white,
                            onPressed: () {
                              assign(2);
                            },
                          )),
                    )
                  : new Container(height: 0),
              is_accpect == "0" && role == '1'
                  ? Padding(
                      padding: new EdgeInsets.fromLTRB(35, 0, 35, 20),
                      child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: new RaisedButton.icon(
                            icon: new Image.asset(
                                'resource/images/user/answer.png'),
                            label: Text(
                              '指派到站点',
                              style: TextStyle(fontSize: 15),
                            ),
                            color: Color.fromRGBO(33, 192, 193, 1),
                            textColor: Colors.white,
                            onPressed: () {
                              assign(1);
                            },
                          )),
                    )
                  : new Container(height: 0),
             int.parse(statuscode) > 0 && isstart=="1" ? Padding(
                      padding: new EdgeInsets.fromLTRB(35, 0, 35, 20),
                      child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: new RaisedButton.icon(
                            icon: new Image.asset(
                                'resource/images/user/answer.png'),
                            label: Text(
                              '查看结果',
                              style: TextStyle(fontSize: 15),
                            ),
                            color: Color.fromRGBO(33, 192, 193, 1),
                            textColor: Colors.white,
                            onPressed: () {
                              setStart();
                            },
                          )),
                    )
                  : new Container(height: 0),
            ],
          ),
        ));
  }
}
